package org.neuedu.dao;

import org.neuedu.bean.Reply;
import org.neuedu.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class ReplyDaoImpl implements ReplyDao {
    @Override
    public int saveReplyInfo(Reply reply) {
        Connection conn = null;
        PreparedStatement ps = null;
        int count = 0;
        try {
            conn = DBUtils.getInstance().getConnection();
            conn.setAutoCommit(false);
            String sql = "insert into reply(aid,uid,replyContent) values (?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setInt(1,reply.getAid());
            ps.setInt(2, reply.getUid());
            ps.setString(3,reply.getReplyContent());
            count = ps.executeUpdate();
            conn.commit();
        }catch (Exception e){
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            DBUtils.getInstance().close(ps);
            DBUtils.getInstance().close(conn);
        }
        return count;
    }

    @Override
    public int updateReplyNum(Reply reply) {
        Connection conn = null;
        PreparedStatement ps = null;
        int count = 0;
        try {
            conn = DBUtils.getInstance().getConnection();
            conn.setAutoCommit(false);
            String sql = "update article set replynum = replynum + 1 where id = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1,reply.getAid());
            count = ps.executeUpdate();
            conn.commit();
        }catch (Exception e){
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            DBUtils.getInstance().close(ps);
            DBUtils.getInstance().close(conn);
        }
        return count;
    }
}
